package com.hongyun.tms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongyun.tms.common.PageResponseDto;
import com.hongyun.tms.common.constants.DefaultCreateByConstant;
import com.hongyun.tms.common.dto.mstaff.MStaffQueryDto;
import com.hongyun.tms.common.dto.mstaff.MStaffSaveReqDto;
import com.hongyun.tms.common.enums.BizCode;
import com.hongyun.tms.common.utils.DateUtils;
import com.hongyun.tms.common.utils.MapperingUtils;
import com.hongyun.tms.common.vo.MStaffVO;
import com.hongyun.tms.entity.MStaff;
import com.hongyun.tms.entity.TmsMTug;
import com.hongyun.tms.exception.BusinessRuntimeException;
import com.hongyun.tms.mapper.MStaffMapper;
import com.hongyun.tms.service.IMStaffService;
import com.hongyun.tms.service.TmsMTugService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工信息表 服务实现类
 * </p>
 *
 * @author liPeng
 * @since 2024-06-05
 */
@Service
public class MStaffServiceImpl extends ServiceImpl<MStaffMapper, MStaff> implements IMStaffService {

//    @Resource
//    private TmsCrewTugService crewTugService;

    @Resource
    private TmsMTugService tugService;
//    @Resource
//    private IProdTugHeadService tugHeadService;

//    @Resource
//    private TmsCrewTugLogService logService;

    @Override
    public PageResponseDto<MStaffVO> pageList(MStaffQueryDto query) {
        // 创建分页对象
        Page<MStaff> page = new Page<>(query.getStartPage(), query.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<MStaff> queryWrapper = new LambdaQueryWrapper<MStaff>()
                .like(StringUtils.isNotBlank(query.getStaffName()), MStaff::getStaffName, query.getStaffName())
                .eq(StringUtils.isNotBlank(query.getSex()), MStaff::getSex, query.getSex())
                .eq(StringUtils.isNotBlank(query.getPostCode()), MStaff::getPostCode, query.getPostCode())
                .eq(query.getTugId() != null, MStaff::getTugId, query.getTugId())
                .eq(query.getStatus() != null, MStaff::getStatus, query.getStatus())
                .eq(query.getDeptId() != null, MStaff::getDeptId, query.getDeptId());

        // 执行分页查询
        baseMapper.selectPage(page, queryWrapper);

        // 构建分页响应
        PageResponseDto<MStaffVO> pageResponseDto = new PageResponseDto(page, MStaffVO.class);

        // 关联查询拖轮信息
        Set<Long> tugIdSet = page.getRecords().stream().map(MStaff::getTugId).collect(Collectors.toSet());
        if (CollectionUtils.isNotEmpty(tugIdSet)) {
            List<TmsMTug> tugList = tugService.list(new LambdaQueryWrapper<TmsMTug>().in(TmsMTug::getId, tugIdSet));
            //用Map将拖轮ID和名称进行关联
            Map<Long, String> tugMap = tugList.stream().collect(Collectors.toMap(TmsMTug::getId, TmsMTug::getTugName));
            // 设置拖轮名称
            pageResponseDto.getRecords().forEach(record -> record.setTugName(tugMap.get(record.getTugId())));
        }
        return pageResponseDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> ids) {
        //删除前的校验
        referenceCheck(ids);
        removeByIds(ids);
    }

    private void referenceCheck(List<String> staffIdList) {
        //船上船员-check
//        ReferenceCheckUtil.checkReference(crewTugService, TmsCrewTug::getStaffId, staffIdList, DeleteReferenceConstant.CREW_TUG_MENU, MStaff::getStaffName, id -> getOne(new LambdaQueryWrapper<MStaff>().eq(MStaff::getId, id)));
        //拖轮负责人-check
//        ReferenceCheckUtil.checkReference(tugHeadService, ProdTugHead::getStaffId, staffIdList, DeleteReferenceConstant.TUG_HEAD_MENU, MStaff::getStaffName, id -> getOne(new LambdaQueryWrapper<MStaff>().eq(MStaff::getId, id)));
        // 上下船记录-check
//        ReferenceCheckUtil.checkReference(logService, TmsCrewTugLog::getStaffId, staffIdList, DeleteReferenceConstant.CREW_TUG_LOG_MENU, MStaff::getStaffName, id -> getOne(new LambdaQueryWrapper<MStaff>().eq(MStaff::getId, id)));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateStaff(MStaffSaveReqDto dto) {
        // 员工编号唯一性检查
        long noCount = this.count(new LambdaQueryWrapper<MStaff>()
                .eq(MStaff::getStaffNo, dto.getStaffNo().trim())
                .ne(dto.getId() != null, MStaff::getId, dto.getId())
        );
        if (noCount > 0) {
            throw new BusinessRuntimeException(BizCode.SYSTEM_ERROR, "员工编号：" + dto.getStaffNo() + "已存在");
        }
        // 保存或更新员工信息
        MStaff mStaff = MapperingUtils.copyProperties(dto, MStaff.class)
                .setUpdateTime(LocalDateTime.now())
                .setUpdateBy(DefaultCreateByConstant.userId)
                .setUpdateByName(DefaultCreateByConstant.userId.toString())
                .setBirthDay(DateUtils.str2LocalDate(dto.getBirthDay()))
                .setEntryDate(DateUtils.str2LocalDate(dto.getEntryDate()));

        if (dto.getId() == null) {
            mStaff.setCreateBy(DefaultCreateByConstant.userId);
            mStaff.setCreateByName(DefaultCreateByConstant.userId.toString());
            mStaff.setCreateTime(LocalDateTime.now());
            this.save(mStaff);
        } else {
            this.updateById(mStaff);
        }
    }
}
